const jwt = require("jsonwebtoken");
const { User } = require("../models");
const { success, failure } = require("../utils/response");
const { Unauthorized } = require('http-errors');
const logger = require("../utils/logger");

module.exports = async (req, res, next) => {
  try {
    // 判断 Token 是否存在
    const { token } = req.headers;
    console.log("token",token)

    if (!token) {
      throw new Unauthorized("当前接口需要认证才能访问。");
    }
    // 验证token是否正确
    logger.info("secret",process.env.SECRET)
    console.log("secret2",process.env.SECRET)
    const decode = jwt.verify(token, process.env.SECRET,);
    console.log("decode",decode)
    // 从 jwt 中，解析出之前存入的userId
    const {userId} = decode

    // 如果通过验证，将userId挂载到req上，方便后续中间件或路由使用
    req.userId = userId;
    // 一定要加next()，才能继续进入到后续中间件或路由
    next();
  } catch (error) {
    failure(res, error);
  }
};
